package com.warehouse.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import com.warehouse.dao.ProductDao;
import com.warehouse.domain.Product;
import com.warehouse.util.DBUtil;

public class ProductDaoImpl implements ProductDao{

	 /**
     * 判断对象是否存在
     * @param obj 商品对象实例
     * @return flag 对象是否存在
     */
	@Override
	public boolean isExist(Product obj)
	{
		boolean flag = false;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			conn = DBUtil.getConnection();  
			pstmt = conn.prepareStatement("select count(ids) from product where ids = ?");
			pstmt.setString(1, obj.getIds()); 
			rs = pstmt.executeQuery();  
			
            //根据变量count取值判定对象是否存在
			if (rs.next()) {
				int count = rs.getInt(1);
				if (count > 0)
					flag = true;
				else
					flag = false;
			} 
			else
				flag = false;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.release(conn, pstmt, rs);
		}
		return flag;
	}

	/**
	 * 功能：新增记录
	 * @param obj 商品对象实例
	 * @return flag 新增成功是否成功
	 */
	@Override
	public boolean add(Product obj) {
		
		if (obj.getIds()==null) {
			System.out.println("主键不能为空");
			return false;
		}

		if (isExist(obj)) {
			System.out.println("记录已存在");
			return false;
		}

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		boolean flag = false;
		
		try {
			conn = DBUtil.getConnection(); //连接数据库			
			pstmt = conn.prepareStatement("insert into product values(?,?,?)"); //预加载sql语句
			//绑定变量值
			pstmt.setString(1, obj.getIds());
			pstmt.setString(2, obj.getProductIds());
			pstmt.setString(3, obj.getProductNumber());
			pstmt.setString(4, obj.getProductName());
			pstmt.setString(5, obj.getProductSpec());
			pstmt.setString(6, obj.getProductUnit());
			pstmt.setInt(7, obj.getType());
	
			pstmt.setDouble(8, obj.getNumber());
			pstmt.setDouble(9, obj.getUnitPrice());
			pstmt.setDouble(10, obj.getMoney());
			pstmt.setDate(11, obj.getTime());
			
			
		
			Double number;
			Double unitPrice;
			Double money;
			Date time;
			
			
			
			
			
			if (pstmt.executeUpdate() == 1) //执行插入操作
				flag = true;
			else
				flag = false;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			DBUtil.release(conn, pstmt, rs);
		}
		return flag;
	}

	@Override
	public boolean del(Product obj) {
		return false;
	}

	@Override
	public boolean update(Product obj) {
		return false;
	}

	@Override
	public Product getObjecByIds(String ids) {
		return null;
	}

	@Override
	public ArrayList<Product> getList() {
		return null;
	}
		
}
